<?php

namespace Api\Controller;

use Think\Controller;

// 跨域
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers:x-requested-with, content-type,token');
class LoginController extends Controller
{

    // 检查账号密码
    function check()
    {
        // 是否为空
        $username = $_POST['username'];
        $password = $_POST['password'];
        $verify = $_POST['verify'];
        if (!$username or !$password or !$verify) $this->ajaxReturn(['state' => 0, 'info' => '请检查数据是否输入正确']);

        // 验证码
        if (!$this->check_verify($verify)) $this->ajaxReturn(['state' => 0, 'info' => '验证码错误']);

        // 账号密码
        $where['username'] = $username;
        $where['password'] = $password;
        $user = M('user')->where($where)->find();
        if (!$user) $this->ajaxReturn(['state' => 0, 'info' => '账号或密码错误']);
        unset($user['password']);

        // 记录登录状态
        $token = md5($username . $password);
        unset($where['password']);
        $login = M('login')->where($where)->find();
        $data['update_time'] =  date("Y-m-d H:i:s");
        $data['token'] = $token;
        // 默认过期7天
        $data['expire_time'] = date('Y-m-d H:i:s', strtotime("+7 day"));
        if ($login) {
            M('login')->where($where)->save($data);
        } else {
            $data['username'] = $username;
            $data['addtime'] = date("Y-m-d H:i:s");
            M('login')->add($data);
        }
        $this->ajaxReturn(['state' => 1, 'info' => '登录成功', 'data' => $user, 'token' => $token]);
    }

    // 获取验证码
    function get_verify()
    {
        // 清楚缓冲区,解决验证码不显示的BUG
        ob_clean();
        $Verify = new \Think\Verify();
        $Verify->useCurve = false;
        $Verify->length = 4;
        $Verify->fontttf = '4.ttf';
        $Verify->entry();
    }

    // 检测验证码
    function check_verify($code)
    {
        $verify = new \Think\Verify();
        return $verify->check($code);
    }


    // 所有函数入口
    function _initialize()
    {
        // 白名单
        $whitelist = ['check', 'get_verify'];
        $url = explode('/', $_SERVER['PATH_INFO']);
        $method = $url[count($url) - 1];
        // 需要验证token
        if (!in_array($method, $whitelist)) {
            $token = $_SERVER['HTTP_TOKEN'];
            $where['token'] = $token;
            $where['expire_time'] = ['gt', date("Y-m-d H:i:s")];
            $login = M('login')->where($where)->find();
            if (!$login) $this->ajaxReturn(['state' => 0, 'info' => '登录已失效 , 请重新登录']);
        }
    }
}
